package com.sandmens.droidvdr;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;


public class main extends ListActivity {

	private ArrayList<HashMap<String,String>> list_bouquet = new ArrayList<HashMap<String,String>>();
	private ArrayList<HashMap<String,String>> list_channel = new ArrayList<HashMap<String,String>>();
	private SimpleAdapter adapEntries_bouquet = null;
	private SimpleAdapter adapEntries_channel = null;
	private ListView channels_list_view;
	
	private ViewFlipper flipper_main_channel;
	private boolean main_recordings_is_Active = false;
	
	private ArrayList<String> Bouquet_name;
	private ArrayList<String> Bouquet_url;
	private ArrayList<String> Channel_name;
	private ArrayList<String> Channel_url;
	private ArrayList<String> EPG_Channel;
	private ArrayList<String> SUB_EPG_Channel;
	 
    private ProgressDialog myProgressDialog = null;
  	private Integer BouquetIdForDownloading; 
  	private String myLine = "";
  	private String Bouquet_Name ="";
  	private String Bouquet_URL = "";
  	private String Channel_Name ="";
  	private String Channel_URL = "";
  	private Integer StartPos = 0;
  	private Integer EndPos = 0;
  	private Integer n = 0;
  	private File File_Handler = null;
  	private Boolean need_download_bouquet = false; 
  	private Boolean need_download_channel = false; 
  	private String Error_Description = "";
  	private String EPG_Title = "";
  	private String EPG_SubTitle = "";
  	private Boolean Use_MovieView = false;
  	private Boolean Use_UTF8 = false;

  	public static final String PREFS_NAME = "droidVDRsettings";
	private Boolean chk_Network1 = false;
	private Boolean chk_Network2 = false;
	
	private String URL_mvdr1 = "http://server-ip:8080/cgi-bin/mvdr.pl"; 
	private String URL_stream1 = "rtsp://vlc-rtsp-ip:1235/test.sdp";
	private String URL_mvdr2 = "http://server-ip:8080/cgi-bin/mvdr.pl"; 
	private String URL_stream2 = "rtsp://vlc-rtsp-ip:1235/test.sdp";
	private static String URL_mvdr = "http://server-ip:8080/cgi-bin/mvdr.pl"; 
	private String URL_stream = "rtsp://vlc-rtsp-ip:1235/test.sdp";

	private String URL_start_vlc = "";
	private boolean Show_EPG_in_Channels_List = true;
	private boolean Coming_from_Settings = false;
	private boolean Coming_from_Player = false;
	private Integer Selected_Channel_Index = 0;
	private boolean Use_MediaView = false;
	/* State for Connection*/
    private String State_Connection_Message = "";
    private ConnectivityManager con_manager;
    private NetworkInfo[] netInfo_array;
    private Integer NetworkSpeed_Availible = -1;
    private boolean Use_AutoSpeed = false;
    private boolean Use_High = false;
    private boolean Use_Middle = false;
    private boolean Use_Low = false;
    private boolean Check_Passwd = false;
    private String HTML_Passwd = "";
    private String HTML_User = "";
	private String login = "";
	private String password = "";

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Error_Description = "";
        Integer n;
        ReadSettings();
        flipper_main_channel = (ViewFlipper) findViewById(R.id.flipper_main_channels_);
        // Get the arrays locally
        Bouquet_name = new ArrayList<String>();
        Bouquet_url  = new ArrayList<String>();
        
        if ( Check_Download_Folder() )
        {
        	Integer res = Check_Download_Folder_Bouquet(true);
        	switch (res)
        	{
        		/*Leeres File */
        		case -1:
        			Bouquet_name.add("Download Bouquet!");
        			Bouquet_url.add("");
                    for (n = 0; n < Bouquet_name.size(); n++) {
                        AddEntry_bouquet(Bouquet_name.get(n), Bouquet_url.get(n));
                    }
                    RefreshList_bouquet();
        			break;
        		/*Bouquet vorhanden*/
        		case 0:
                	BouquetProcessing();        
        			break;
        		/* Fehler */
        		case 1:
        			break;
        	}
        }
    }
    
  	private void ReadSettings()
  	{
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        chk_Network1 = settings.getBoolean("network1_active", false);
    	URL_mvdr1 = settings.getString("network1_url_mvdr", "http://xx.com/cgi-bin/mvdr.pl");
    	URL_stream1 = settings.getString("network1_url_stream", "rtsp://xx.com/test.sdp");
        chk_Network2 = settings.getBoolean("network2_active", false);
    	URL_mvdr2 = settings.getString("network2_url_mvdr", "http://xx.com/cgi-bin/mvdr.pl");
    	URL_stream2 = settings.getString("network2_url_stream", "rtsp://xx.com/test.sdp");
    	Use_MediaView = settings.getBoolean("use_camera_player", false);
    	if (chk_Network1 )
    	{
    		URL_mvdr = URL_mvdr1;
    		URL_stream = URL_stream1;
    	}
    	else if (chk_Network2 )
    	{
    		URL_mvdr = URL_mvdr2;
    		URL_stream = URL_stream2;
    	}
    	Use_AutoSpeed = settings.getBoolean("network_use_auto", false);
    	
    	if ( chk_Network1 )
    	{
	    	Check_Passwd = settings.getBoolean("network1_use_passwd", false);
	    	if ( Check_Passwd )
	    	{
		    	HTML_User = settings.getString("network1_user", "user");
		    	HTML_Passwd = settings.getString("network1_passwd", "passwd");
	    	}
    	}
    	if ( chk_Network2 )
    	{
	    	Check_Passwd = settings.getBoolean("network2_use_passwd", false);
	    	if (Check_Passwd )
	    	{
		    	HTML_User = settings.getString("network2_user", "user");
		    	HTML_Passwd = settings.getString("network2_passwd", "passwd");
	    	}
    	}
    	Use_UTF8 = settings.getBoolean("use_utf8", false);

  	 }
  	
  	private boolean Check_Download_Folder()
  	{
  		File directory = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr");
  		if (!directory.exists()) 
  		{
            if ( directory.mkdir() == false )
            {
    	    	Toast toast = Toast.makeText(getApplicationContext(), "Error create Folder", Toast.LENGTH_SHORT);
    	    	toast.show();
            }
  		}
  		
  		return true;
  	}
  	
  	private Integer Check_Download_Folder_Bouquet(Boolean Create_File)
  	{
  		try
  		{
	  		File File_Bouquet = new File
	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_bouquet.pl");
	  		if ( File_Bouquet.exists() )
	  		{
	  			if (File_Bouquet.length()>0 )
	  				return 0;
	  			else
	  				return -1;
	  		}
  		}
  		catch ( Exception ex)
  		{
	    	System.out.println(ex.toString());
	    	Toast toast = Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT);
	    	toast.show();
	  		return 1;
  		}
  		return 1;
  	}

  	@Override
    public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
   
    private Integer Check_Network()
    {
		con_manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); 
		if ( con_manager == null)
		{
			State_Connection_Message = "no comManager active";
			return -1;
		}
		netInfo_array = con_manager.getAllNetworkInfo();
		if (netInfo_array == null)
		{
			State_Connection_Message = "con_manager: no networkinfo availible";
			return -1;
		}
		Integer i =0;
		String net_info_Name ="";
		boolean One_Is_Connected = false;
        for (i = 0; i < netInfo_array.length; i++) {
        	
        	if ( netInfo_array[i].isConnected() )
        	{
        		One_Is_Connected = true;
        		net_info_Name = netInfo_array[i].getTypeName();
        		if ( net_info_Name.equalsIgnoreCase("WIFI"))
        		{
        			State_Connection_Message = "WIFI is Active High Res.";
        			NetworkSpeed_Availible = 1;
        			return 1;
        		}
        		else if  ( net_info_Name.equalsIgnoreCase("MOBILE"))
        		{
        			Integer sub_type = netInfo_array[i].getSubtype();
        			if  (( sub_type == TelephonyManager.NETWORK_TYPE_HSDPA ) || ( sub_type == TelephonyManager.NETWORK_TYPE_UMTS ))
        			{
	        			State_Connection_Message = "UMTS is Active middle Res.";
	        			NetworkSpeed_Availible = 2;
	        			return 2;
        			}
        			else if ( sub_type == TelephonyManager.NETWORK_TYPE_EDGE )
        			{
	        			State_Connection_Message = "EDGE is Active low Res.";
	        			NetworkSpeed_Availible = 3;
	        			return 3;
        			}
        			else
        			{
	        			State_Connection_Message = "no possible connection :-(";
	        			NetworkSpeed_Availible = 4;
	        			return 4;
        			}
        		}
        	}
        }
        if (!One_Is_Connected )
        {
			State_Connection_Message = "no possible connection :-(";
			NetworkSpeed_Availible = 0;
			return 0;
        }
    	
    	return -1;
    }
    
    @Override
    protected void onStop(){
    	super.onStop();
    }

    @Override
    protected void onStart()
    {
    	super.onStart();
    }
    
    @Override
    protected void onRestart()
    {
    	super.onRestart();
    }

	@Override
    protected void onResume()
    {
		super.onResume();
		if (Coming_from_Settings)
		{
			Coming_from_Settings = false;
			ReadSettings();
	    	BouquetProcessing();
		}
		if ( Coming_from_Player)
		{
			Coming_from_Player = false;
	        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			PlayerStopProcessing();
		}
    }
    
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	  if (resultCode == Activity.RESULT_OK && requestCode == 0) 
	  {

	    Bundle extras = data.getExtras();
	    String result = extras.getString("ACTION");
	    if ( result.equalsIgnoreCase("RELOAD_SETTINGS"))
	    {
	    	Coming_from_Settings = true;
	    }
	  }
	  else if (requestCode == 9988) 
	  {
		  Coming_from_Player = true;
	  }
	}

	@Override
    protected void onPause()
    {
    	super.onPause();
    }
    
    @Override
    protected void onDestroy()
    {
    	super.onDestroy();
    }
    
    public void AddEntry_bouquet(String name, String url) {
             HashMap<String,String> newitem = new HashMap<String,String>();
             newitem.put( "bouquet_name", name );
             newitem.put( "bouquet_url", url );
             list_bouquet.add( newitem );
       }

    public void RefreshList_bouquet() 
    {
           SimpleAdapter adapEntries_bouquet = new SimpleAdapter(
                  this,
                  list_bouquet,
                  R.layout.bouquet_row,
                  new String[] { "bouquet_name", "bouquet_url" },
                  new int[] { R.id.txtBouquetName, R.id.txtBouquetUrl}
                  );
             setListAdapter(adapEntries_bouquet);
       } 

    public void AddEntry_channel(String name, String url) {
        HashMap<String,String> newitem = new HashMap<String,String>();
        newitem.put( "channel_name", name );
        newitem.put( "channel_url", url );
        list_channel.add( newitem );
  }
    
    public void RefreshList_channel() 
    {
        SimpleAdapter adapEntries_channel = new SimpleAdapter(
        	   this,
               list_channel,
               R.layout.channel_row,
               new String[] { "channel_name", "channel_url" },
               new int[] { R.id.txtChannelName, R.id.txtChannelUrl}
               );
        channels_list_view = (ListView) findViewById(R.id.android_list_channels);
        channels_list_view.setAdapter(adapEntries_channel);

        channels_list_view.setOnItemLongClickListener(new OnItemLongClickListener ()
        {
        	public boolean onItemLongClick  (AdapterView av, View view, int position, long id)
        	{
	       		Toast messageToast = Toast.makeText(getApplicationContext(), EPG_Channel.get(position) + "\n" + SUB_EPG_Channel.get(position), Toast.LENGTH_LONG);
	    		messageToast.show();
        		return true;
        	}
        });
        
        channels_list_view.setOnItemClickListener(new OnItemClickListener()
        {
        	public void onItemClick( AdapterView av, View v, int position, long id)
        	{
        		if ( id == 0 )
        		{
        			flipper_main_channel.setInAnimation(inFromLeftAnimation());
        			flipper_main_channel.setOutAnimation(outToRightAnimation());
        			flipper_main_channel.showPrevious();
        		}
        		else
        		{
        			Selected_Channel_Index = position;
        			AlertDialog.Builder ad = new AlertDialog.Builder( main.this );
        			ad.setTitle( "Start streaming...?" );
        	     	if ( !Use_AutoSpeed )
        	    	{
        				Integer Speed = Check_Network();
        				Integer Pre_Select = 0;
        				if ( Speed == 1)
        				{
        					Use_High = true;
        					Use_Middle = false;
        					Use_Low = false;
        					Pre_Select = 0;
        				}
        				else if ( Speed == 2)
        				{
        					Use_High = false;
        					Use_Middle = true;
        					Use_Low = false;
        					Pre_Select = 1;
        				}
        				else if ( Speed == 3)
        				{
        					Use_High = false;
        					Use_Middle = false;
        					Use_Low = true;
        					Pre_Select = 2;
        				}
        				else
        				{
        					Use_High = false;
        					Use_Middle = false;
        					Use_Low = true;
        					Pre_Select = 2;
        				}
        				 final String[] items_question_coonection = {"Fast", "Middle", "Slow"};
        				 ad.setSingleChoiceItems(items_question_coonection , Pre_Select, new DialogInterface.OnClickListener() 
        				 {
        				        public void onClick(DialogInterface dialog, int item)
        				        {
        					          if ( item == 0)
        					          {
        									Use_High = true;
        									Use_Middle = false;
        									Use_Low = false;
        					          }
        					          else if ( item == 1)
        					          {
        									Use_High = false;
        									Use_Middle = true;
        									Use_Low = false;
        					          }
        					          else if ( item == 2)
        					          {
        									Use_High = false;
        									Use_Middle = false;
        									Use_Low = true;
        					          }
        				        }
        			    });
        				 ad.setPositiveButton( "Yes", new DialogInterface.OnClickListener() 
        				 {
        		             public void onClick(DialogInterface dialog, int id) 
        		             {
        		        	     PlayerProcessing();
        		             }
        				 });
        				 ad.setNegativeButton( "No",  new DialogInterface.OnClickListener() 
        				 {
        		             public void onClick(DialogInterface dialog, int id) 
        		             {
        		            	 return;
        		             }
        				 });
        				 ad.show();
        	    	}
        		}
        	}
    	});
     } 
    
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if ( keyCode == KeyEvent.KEYCODE_BACK)
		{
			if ( !main_recordings_is_Active)
			{
				if ( channels_list_view != null )
				{
					if ( channels_list_view.hasFocus() )
					{
						flipper_main_channel.setInAnimation(inFromLeftAnimation());
						flipper_main_channel.setOutAnimation(outToRightAnimation());
						flipper_main_channel.showPrevious();
						return true;
					}
				}
			}
		}			
		return super.onKeyDown(keyCode, event);
	}

    @Override
    protected void onListItemClick(ListView l,View v,int position,long id) 
    {
    	TextView textView = (TextView) v.findViewById(R.id.txtBouquetName); 
        String text = textView.getText().toString();
        if (text == "Download Bouquet!")
        {
        	Error_Description = "";
        	BouquetProcessing();
        }
        else if (text == "Recordings")
        {
			Intent recordingsActivity = new Intent(getBaseContext(), Recordings.class);
			recordingsActivity.putExtra("URL", URL_mvdr);
			recordingsActivity.putExtra("STREAM_URL", URL_stream);
			startActivityForResult(recordingsActivity,2);
        }
        else
        {
        	Error_Description = "";
        	int cast_int = (int)id;
        	ChannelProcessing(cast_int);
        }
    } 
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	super.onCreateOptionsMenu(menu);
    	menu.add(0,0,0, "setting");
    	menu.add(0,1,0, "VDR Power OFF");
    	menu.add(0,2,0, "VDR Power ON");
    	menu.add(0,3,0, "Exit");
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch (item.getItemId())
    	{
    		case 0:
				Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
				startActivityForResult(settingsActivity,0);
    			return true;
    			
    		case 1:
    			SwitchOffProcessing();
				return true;

    		case 2:
				
				return true;

    		case 3:
				finish();
				return true;
    	}
    	return true;
    }

    private Animation inFromRightAnimation() 
    {
    	Animation inFromRight = new TranslateAnimation(
    	Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
    	Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
    	);
    	inFromRight.setDuration(500);
    	inFromRight.setInterpolator(new AccelerateInterpolator());
    	return inFromRight;
	}

	private Animation outToLeftAnimation()
	{
    	Animation outtoLeft = new TranslateAnimation(
    	 Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
    	 Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
    	);
    	outtoLeft.setDuration(500);
    	outtoLeft.setInterpolator(new AccelerateInterpolator());
    	return outtoLeft;
	}

	private Animation inFromLeftAnimation() 
	{
		Animation inFromLeft = new TranslateAnimation(
		Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
		Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		inFromLeft.setDuration(500);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;
	}

	private Animation outToRightAnimation() 
	{
		Animation outtoRight = new TranslateAnimation(
		 Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
		 Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		outtoRight.setDuration(500);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;
	}	
	
    private void BouquetProcessing() 
    {
    	Error_Description = "";
        Thread thread =  new Thread(null, doBackgroundBouquet, "GenerateBouquet");
        need_download_bouquet = true;
        try
        {
        	File_Handler = new File
  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_bouquet.pl");
	        if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
	        {
	        	need_download_bouquet = false;
	        }
        }
        catch ( Exception ex)
        {
        	need_download_bouquet = true;
        }
        if ( need_download_bouquet )
        {
	        myProgressDialog = ProgressDialog.show(main.this,    
	              "Please wait...", "downloading files...", true);
        }
        else
        {
	        myProgressDialog = ProgressDialog.show(main.this,    
		              "Please wait...", "parsing files...", true);
        }
        thread.start();
   }

    private Runnable doBackgroundBouquet = new Runnable(){
    	public void run()
    	{
            if ( need_download_bouquet )
            {
	    		/*
	    		 * Erster Teil vom Thread
	    		 */
	            try
	            {
	            	downloadFile(0,"");
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                	 if ( Error_Description == "" )
	                	 {
	                		 myProgressDialog.setMessage("parsing files...");
	                	 }
	                	 else
	                	 {
		                     myProgressDialog.dismiss();
	                		 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                		 messageToast.show();
	                		 return;
	                	 }
	                 }        
	            	});
            }
			if ( Error_Description == "" )
			{
	            try
	            {
	            	read_bouquet();
	            } 
	            catch (Exception ex) 
	            {  
	            	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                	 if ( Error_Description == "" )
	                	 {
	                		 RefreshList_bouquet();
		                     myProgressDialog.dismiss();
	                	 }
	                	 else
	                	 {
	                		 myProgressDialog.dismiss();
	                		 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                		 messageToast.show();
	                		 RefreshList_bouquet();
	                	 }
	                 }        
	          });
			}
    	}
  }; 

  	private void read_bouquet() throws IOException
  	{
  		File_Handler = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_bouquet.pl");
        Bouquet_name.clear();
        Bouquet_url.clear();
        list_bouquet.clear();
        Integer StartPosInLine = 0;
        try {
            if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) {
    			Bouquet_name.add("Recordings");
    			Bouquet_url.add("");
                BufferedReader r = null;
    			if ( Use_UTF8 )
    				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
    			else
    				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
                while ((myLine =r.readLine()) != null)
                {
                    StartPosInLine = 0;
                    if (myLine.contains("bouquet_channels+") )
                    {
                    	while (StartPosInLine >= 0)
                    	{
	                    	StartPos = myLine.indexOf('?', StartPosInLine);
	                    	if (StartPos >0 )
	                    	{
		                    	EndPos = myLine.indexOf('\'', StartPos+1);
		                    	Bouquet_URL = myLine.substring(StartPos+1, EndPos);
		                    	StartPos = EndPos +1;
		                    	EndPos = myLine.indexOf('<', StartPos);
		                    	StartPosInLine = EndPos;
		                    	Bouquet_Name = myLine.substring(StartPos+1, EndPos);
		                    	Bouquet_name.add(Bouquet_Name);
		                    	Bouquet_url.add(URL_mvdr + "?" + Bouquet_URL);
	                    	}
	                    	else
	                    	{
	                    		StartPosInLine = -1;
	                    	}
                    	}
                    }
                }
                
                for (n = 0; n < Bouquet_name.size(); n++) {
                    AddEntry_bouquet(Bouquet_name.get(n), Bouquet_url.get(n));
                }
            }
        }
        catch (Exception ex)
        {
            Bouquet_name.clear();
            Bouquet_url.clear();
            list_bouquet.clear();
			Bouquet_name.add("Download Bouquet!");
			Bouquet_url.add("");
			Bouquet_name.add("Recordings");
			Bouquet_url.add("");
            for (n = 0; n < Bouquet_name.size(); n++) {
                AddEntry_bouquet(Bouquet_name.get(n), Bouquet_url.get(n));
            }
        	Error_Description = ex.getMessage().toString();
        	System.out.println(ex.toString());
        }
        finally 
        {
        }

  	}
  	
    private void ChannelProcessing(Integer BouquetId) 
    {
    	BouquetIdForDownloading = BouquetId;
        Thread thread =  new Thread(null, doBackgroundChannel, "GenerateChannels");
        need_download_channel = true;
        try
        {
        	File_Handler = new File
  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_channels_" + BouquetId.toString() + ".htm");
	        if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
	        {
	        	need_download_channel = false;
	        }
        }
        catch (Exception ex)
        {
        	need_download_channel = true;
        }
        
        if ( need_download_channel)
        {
	        myProgressDialog = ProgressDialog.show(main.this,    
	              "Please wait...", "downloading files...", true);
        }
        else
        {
	        myProgressDialog = ProgressDialog.show(main.this,    
		              "Please wait...", "parsing files...", true);
        }
        
        thread.start();

   }

    private Runnable doBackgroundChannel = new Runnable(){
    	public void run()
    	{
    		if ( need_download_channel)
    		{
	    		/*
	    		 * Erster Teil vom Thread
	    		 */
	            try
	            {
	            	String new_url = Bouquet_url.get(BouquetIdForDownloading);
	            	Integer new_url_last_part_pos = new_url.indexOf('?');
	            	Integer new_url_last_part_end_pos = new_url.length();
	            	String new_url_last_part = URL_mvdr + new_url.substring(new_url_last_part_pos, new_url_last_part_end_pos);
	            	downloadFile(1,new_url_last_part);
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 public void run() {
	                	 if ( Error_Description == "" )
	                	 {
	                		 myProgressDialog.setMessage("parsing files...");
	                	 }
	                	 else
	                	 {
		                     myProgressDialog.dismiss();
	                		 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                		 messageToast.show();
	                		 return;
	                	 }
	                 }        
	            	});

    		}

	       	 if ( Error_Description == "" )
	    	 {
	    		try
	            {
	            	read_channel(BouquetIdForDownloading);
	            } 
	            catch (Exception ex) 
	            {  
	            	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                     RefreshList_channel();
	                     myProgressDialog.dismiss();
	                     flipper_main_channel.setInAnimation(inFromRightAnimation());
	                     flipper_main_channel.setOutAnimation(outToLeftAnimation());
	                     flipper_main_channel.showNext();    
	                 }        
	          });
	    	 }
    	}
  }; 
  
  	private void read_channel(Integer bouquetIdForDownloading) throws IOException
  	{
        File_Handler = new File
        (Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_channels_" + bouquetIdForDownloading.toString() + ".htm");
        if ( Channel_url != null)
        	Channel_url.clear();
        else
        	Channel_url  = new ArrayList<String>();
        
        if ( Channel_name != null)
        	Channel_name.clear();
        else
        	Channel_name = new ArrayList<String>();
        
        if ( list_channel != null)
        	list_channel.clear();
        
        if ( EPG_Channel == null )
        {
        	EPG_Channel = new ArrayList<String>();
        }
        else
        	EPG_Channel.clear();
        if ( SUB_EPG_Channel == null )
        {
        	SUB_EPG_Channel = new ArrayList<String>();
        }
        else
        	SUB_EPG_Channel.clear();
        
        Integer StartPosInLine = 0;
        Channel_name.add("BACK");
        Channel_url.add("back to bouquets");
        
        EPG_Channel.add("BACK");
        SUB_EPG_Channel.add("back to bouquets");
        try 
        {
                if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
                {
                    BufferedReader r = null;
        			if ( Use_UTF8 )
        				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
        			else
        				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
                    while ((myLine =r.readLine()) != null) 
                    {
                    	StartPosInLine = 0;
                        //myLine = dis.readLine();
                        if (myLine.contains("channels+") )
                        {
                        	while (StartPosInLine >= 0)
                        	{
                            	StartPos = myLine.indexOf('?', StartPosInLine);
    	                    	if (StartPos > 0 )
    	                    	{
                                	EndPos = myLine.indexOf('\'', StartPos+1);
                                	Channel_URL = myLine.substring(StartPos+1, EndPos);
                                	StartPos = myLine.indexOf(">->", EndPos)+2;
                                	EndPos = myLine.indexOf('<', StartPos);
                                	Channel_Name = myLine.substring(StartPos+1, EndPos);
                                	Channel_name.add(Channel_Name);
                                	Channel_url.add(URL_mvdr + "?" + Channel_URL);

                                	StartPos = myLine.indexOf("EPG:->", EndPos)+5;
                                	EndPos = myLine.indexOf("->", StartPos+5);
                                	if ( EndPos > 0)
                                	{
                                    	EPG_Title = myLine.substring(StartPos+1, EndPos);
                                    	EPG_Channel.add(EPG_Title);
                                    	EPG_Title="";

                                    	StartPos = myLine.indexOf("->", EndPos);
                                    	EndPos = myLine.indexOf("<", StartPos+1);
                                    	EPG_SubTitle = myLine.substring(StartPos+2, EndPos);
                                    	SUB_EPG_Channel.add(EPG_SubTitle);
                                    	EPG_SubTitle="";
                                	}
                                	else
                                	{
                                    	EPG_Title="no EPG";
                                    	EPG_Channel.add(EPG_Title);
                                    	EPG_Title="";
                                		
                                    	EPG_SubTitle="";
                                    	SUB_EPG_Channel.add(EPG_SubTitle);
                                    	EPG_SubTitle="";
                                	}
                                	StartPosInLine = EndPos;
                                	
    	                    	}
    	                    	else
    	                    	{
    	                    		StartPosInLine = -1;
    	                    	}
                        	}
                        }
                    }
                    for (n = 0; n < Channel_name.size(); n++) 
                    {
                    	if ( !Show_EPG_in_Channels_List )
                    		AddEntry_channel(Channel_name.get(n), Channel_url.get(n));
                    	else
                    		AddEntry_channel(Channel_name.get(n), EPG_Channel.get(n));
                    }
                }
        }
        finally 
        {
            try 
            {
                File_Handler.delete();
            } 
            catch (Exception ex) 
            {
            	System.out.println(ex.toString());
            }
        }

  	}

    private void PlayerProcessing() 
    {
        Thread thread =  new Thread(null, doBackgroundPlayer, "GenerateStream");
        need_download_channel = true;
        try
        {
        	File_Handler = new File
      		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/play.htm");
	        if (File_Handler.exists() ) 
	        {
	        	File_Handler.delete();
	        }
        }
        catch (Exception ex)
        {
        	System.out.println(ex.toString());
        	return;
        }
        
        thread.start();
        
        myProgressDialog = ProgressDialog.show(main.this,    
              "Please wait...", "starting stream...", true);
        
   }

    private Runnable doBackgroundPlayer = new Runnable(){
    	public void run()
    	{
            try
            {
            	if ( Use_AutoSpeed )
            	{
        			Integer Speed = Check_Network();
        			switch (Speed)
        			{
        				case 1:
    	    				URL_start_vlc = Channel_url.get(Selected_Channel_Index)+"+H";
        					break;
        				case 2:
    	    				URL_start_vlc = Channel_url.get(Selected_Channel_Index)+"+M";
        					break;
        				case 3:
    	    				URL_start_vlc = Channel_url.get(Selected_Channel_Index)+"+L";
        					break;
    					default:
    						Error_Description = "Check_Network: No network availible!";
    						break;
        			}
            	}
            	else
            	{
            		if ( Use_High )
            		{
	    				URL_start_vlc = Channel_url.get(Selected_Channel_Index)+"+H";
            		}
            		else if (Use_Middle)
            		{
	    				URL_start_vlc = Channel_url.get(Selected_Channel_Index)+"+M";
            		}
            		else if (Use_Low)
            		{
	    				URL_start_vlc = Channel_url.get(Selected_Channel_Index)+"+L";
            		}
            	}
            } 
            catch (Exception ex) 
            {  
            	System.out.println(ex.toString());
            }
    		
	            try
	            {
	            	downloadFile(2,URL_start_vlc);
		   	       	if ( Error_Description == "" )
			    	{
		   	       		Thread.sleep(1000);
		   	       		read_play_vlc();
			    	}
		   	       	
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }

	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                	 if ( Error_Description == "" )
	                	 {
	                		 if ( !Use_MediaView )
	                		 {
		                		 Intent int_setting = new Intent();
		                		 int_setting.putExtra( "STREAM_URL",URL_stream);
		                		 int_setting.putExtra( "URL",URL_mvdr);
		                		 int_setting.setClass(getApplicationContext(),player.class);
		                		 myProgressDialog.dismiss();
		                		 startActivityForResult(int_setting,9988);
	                		 }
	                		 else
	                		 {
	                			 Uri _uri = Uri.parse(URL_stream);
	                			 Intent int_media_view = new Intent();
	                			 int_media_view.setDataAndType(_uri, "movie/*");
	                			 int_media_view.setClassName("com.cooliris.media", "com.cooliris.media.MovieView");
	                			 int_media_view.setAction(Intent.ACTION_VIEW);
		                		 myProgressDialog.dismiss();
		                		 startActivityForResult(int_media_view,9988);
	                		 }
	                	 }
	                	 else
	                	 {
		                     myProgressDialog.dismiss();
	                		 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                		 messageToast.show();
	                		 return;
	                	 }
	                }        
	            	});

    		
    	}
  }; 
  
  	private void read_play_vlc()
  	{
  		Boolean VLC_is_Streaming = false;
        File_Handler = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/play.htm" );
        try 
        {
                if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
                {
                	try
                	{
                        BufferedReader r = null;
            			if ( Use_UTF8 )
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
            			else
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
	                    while ((myLine =r.readLine()) != null)
	                    {
					        if (myLine.contains("done play :-)") )
					        {
					        	VLC_is_Streaming = true;
					        }
						}
                	}
                	catch ( Exception ex )
                	{
                		Error_Description = ex.getMessage().toString();
                		return;
                	}
                }
        }
        finally 
        {
        }
        if ( !VLC_is_Streaming)
        {
	    	Toast toast = Toast.makeText(getApplicationContext(), "Error start streaming", Toast.LENGTH_SHORT);
	    	toast.show();
        }
    	
        if (File_Handler.exists())
        	File_Handler.delete();

  	}
    
  	private void PlayerStopProcessing() 
    {
        Thread thread =  new Thread(null, doBackgroundPlayer_Stop, "StopStream");
        need_download_channel = true;
        try
        {
        	File_Handler = new File
      		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/stop.htm");
	        if (File_Handler.exists() ) 
	        {
	        	File_Handler.delete();
	        }
        }
        catch (Exception ex)
        {
        	System.out.println(ex.toString());
        	return;
        }
        
        
        myProgressDialog = ProgressDialog.show(main.this,    
              "Please wait...", "stoping stream...", true);
        
        thread.start();
        
   }

    private Runnable doBackgroundPlayer_Stop = new Runnable(){
    	public void run()
    	{
	            try
	            {
	            	 downloadFile(3,"");
	               	 if ( Error_Description == "" )
	            	 {
	            		myProgressDialog.setMessage("parsing files...");
	 	            	read_stop_vlc();
	            	 }
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                     myProgressDialog.dismiss();
	                     if ( Error_Description != "" )
	                     {
	                    	 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                    	 messageToast.show();
	                     }
	                 }        
	            	});

    		
    	}
  }; 
  	
	private void read_stop_vlc()
  	{
  		Boolean VLC_is_Stoped = false;
        File_Handler = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/stop.htm" );
        try 
        {
                if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
                {
                    try 
                    {
                        BufferedReader r = null;
            			if ( Use_UTF8 )
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
            			else
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
	                    while ((myLine =r.readLine()) != null)
						{
					        if (myLine.contains("done stop :-)") )
					        {
					        	VLC_is_Stoped = true;
					        }
						}
					} 
                    catch (Exception ex) 
					{
                    	Error_Description = ex.getMessage().toString();
					}
                }
        }
        finally 
        {
        }
        if ( VLC_is_Stoped )
        {
	    	Toast toast = Toast.makeText(getApplicationContext(), "VLC is streaming stoped", Toast.LENGTH_LONG);
	    	toast.show();
        }
  	}
    
  	private void SwitchOffProcessing() 
    {
        Thread thread =  new Thread(null, doBackgroundSwitchOff, "SwitchOff");
        try
        {
        	File_Handler = new File
      		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/switchOff.htm");
	        if (File_Handler.exists() ) 
	        {
	        	File_Handler.delete();
	        }
        }
        catch (Exception ex)
        {
        	System.out.println(ex.toString());
        	return;
        }
        
        
        myProgressDialog = ProgressDialog.show(main.this,    
              "Please wait...", "switch off...", true);
        
        thread.start();
        
   }

    private Runnable doBackgroundSwitchOff = new Runnable(){
    	public void run()
    	{
	            try
	            {
	            	 downloadFile(5,"");
	               	 if ( Error_Description == "" )
	            	 {
	            		myProgressDialog.setMessage("parsing files...");
	            		read_switch_off();
	            	 }
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                     myProgressDialog.dismiss();
	                     if ( Error_Description != "" )
	                     {
	                    	 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                    	 messageToast.show();
	                     }
	                     else
	                     {
	                    	 Toast messageToast = Toast.makeText(getApplicationContext(), "VDR OFF", Toast.LENGTH_SHORT);
	                    	 messageToast.show();
	                     }
	                    }        
	            	});

    		
    	}
  }; 
  	
	private void read_switch_off()
  	{
        File_Handler = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/switchOff.htm" );
        try 
        {
                if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
                {
                    try 
                    {
                        BufferedReader r = null;
            			if ( Use_UTF8 )
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
            			else
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
	                    while ((myLine =r.readLine()) != null)
						{
					        if (myLine.contains("accept") )
					        {
					        	Error_Description = "";
					        }
						}
					} 
                    catch (Exception ex) 
					{
                    	Error_Description = ex.getMessage().toString();
					}
                }
        }
        finally 
        {
        }
  	}
	
  	private Boolean downloadFile(Integer download_mode, String URL_for_VDR)
  	{
  		if ( Check_Passwd )
  		{
  			login = HTML_User;
  			password = HTML_Passwd;
  		}
  		else
  		{
  			login = "";
  			password = "";
  		}
		Authenticator.setDefault(new Authenticator() 
		{
		    protected PasswordAuthentication getPasswordAuthentication() 
		    {
		    	PasswordAuthentication mypas = null;
		    	try
		    	{
		    		mypas = new PasswordAuthentication (login, password.toCharArray());
		    	}
		    	catch (Exception ex )
		    	{
		    		Log.e("mypas", ex.toString());
		    	}
		        return mypas;
		    }
		});
		
  		Error_Description = "";
    	switch (download_mode)
    	{
    		// Bouquet-�bersicht
    		case 0:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_mvdr + "?bouquet");
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	  		File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_bouquet.pl");
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
    	  	        
    	  	        byte[] buffer = new byte[8192];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) > 0 ) 
    	  	        {
    	  	        	fileOutput.write(buffer,0, len1);
        	  	        fileOutput.flush();
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();
    	  	        
    	  		}
    	  		catch (Exception ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;
    		
			/* Channels vom Bouquet */
    		case 1:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_for_VDR);
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	        File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_channels_" + BouquetIdForDownloading.toString()+ ".htm" );

    	  	  		if (!File_Bouquet.exists())
    	  	  			File_Bouquet.createNewFile();
    	  	  		
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
	    	  	        
    	  	        byte[] buffer = new byte[8192];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) > 0 ) {
    	  	        	fileOutput.write(buffer,0, len1);
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();
    	  	        
    	  		}
    	  		catch (Exception ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;

    		// VLC play
    		case 2:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_for_VDR);
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	        File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/play.htm" );

    	  	  		if (!File_Bouquet.exists())
    	  	  			File_Bouquet.createNewFile();
    	  	  		
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
	    	  	        
    	  	        byte[] buffer = new byte[1024];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) != -1 ) {
    	  	        	fileOutput.write(buffer,0, len1);
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();
    	  		}
    	  		catch (IOException ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;
    			
    		// VLC is Stoping
    		case 3:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_mvdr + "?stop");
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	        File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/stop.htm" );

    	  	  		if (!File_Bouquet.exists())
    	  	  			File_Bouquet.createNewFile();
    	  	  		
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
	    	  	        
    	  	        byte[] buffer = new byte[1024];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) != -1 ) {
    	  	        	fileOutput.write(buffer,0, len1);
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();

    	  	        
    	  		}
    	  		catch (IOException ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;
    			
    		/* GET recording */
    		case 4:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_mvdr + "?rec");
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	  		File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_recording.htm");
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
    	  	      
    	  	        
    	  	        byte[] buffer = new byte[8192];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) > 0 ) 
    	  	        {
    	  	        	fileOutput.write(buffer,0, len1);
    	  	        	
        	  	        fileOutput.flush();
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();
    	  	        
    	  		}
    	  		catch (Exception ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;
    			
        		/* Switch OFF */
    		case 5:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_mvdr + "?hitk+Power");
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	  		File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/switchOff.htm");
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
    	  	      
    	  	        
    	  	        byte[] buffer = new byte[8192];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) > 0 ) 
    	  	        {
    	  	        	fileOutput.write(buffer,0, len1);
    	  	        	
        	  	        fileOutput.flush();
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();
    	  	        
    	  		}
    	  		catch (Exception ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;
    	}
		return true;
  	}

}



